#include "SPI.h"



uint8 SPI::RWByte(uint8 data)
{
	uint8 res = 0;
	if (this->_HighFirst)
	{
		for (size_t i = 0x80; i > 0; i >>= 1)
		{
			digitalWrite(this->_SCK, this->_CPOL);

			if (data & i)
			{
				digitalWrite(this->_MOSI, HIGH);
			}
			else
			{
				digitalWrite(this->_MOSI, LOW);
			}

			digitalWrite(this->_SCK, !this->_CPOL);

			if (!this->_CPHA)
			{
				if (digitalRead(this->_MISO))
					res |= i;
			}
			digitalWrite(this->_SCK, this->_CPOL);
			if (this->_CPHA)
			{
				if (digitalRead(this->_MISO))
					res |= i;
			}
		}
	}
	else
	{
		for (size_t i = 0x01; i < 0x100; i <<= 1)
		{
			digitalWrite(this->_SCK, this->_CPOL);

			if (data & i)
			{
				digitalWrite(this->_MOSI, HIGH);
			}
			else
			{
				digitalWrite(this->_MOSI, LOW);
			}

			digitalWrite(this->_SCK, !this->_CPOL);

			if (!this->_CPHA)
			{
				if (digitalRead(this->_MISO))
					res |= i;
			}
			digitalWrite(this->_SCK, this->_CPOL);
			if (this->_CPHA)
			{
				if (digitalRead(this->_MISO))
					res |= i;
			}
		}
	}

	return res;
}
